<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\AuthenticationException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param \Exception $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Exception $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        //检测是否登录 验证失败时 抛出的异常
        if ($exception instanceof AuthenticationException) {
            if ($request->ajax()) {
                // $exception->status(200);
                return response()->json(['status' => 40001, 'msg' => 'no-login', 'redirect_url' => '/admin/login']);
                // return $this->convertValidationExceptionToResponse($exception, $request);
            }
        }
        return parent::render($request, $exception);
    }

    /**
     * 重写 修改json相应时的格式
     * @param  [type]              $request   [description]
     * @param ValidationException $exception [description]
     * @return \Illuminate\Http\Response | \Symfony\Component\HttpFoundation\Response
     * @author cuibo weiai525@outlook.com at 2018-05-03
     */
    protected function invalidJson($request, ValidationException $exception)
    {
        $message = $exception->getMessage();
        $errors = $exception->errors();
        if (count($errors) > 0) {
            $ls = array_first($errors);
            $message = $ls[0];
        }
        return response()->json([
            'status' => 30001,
            'msg' => $message,
            'errors' => $exception->errors(),
            'auto_msg' => true,
        ], 200);
    }
    // protected function convertValidationExceptionToResponse(ValidationException $e, $request)
    // {
    //     if ($e->response) {
    //         print_r($e->response);
    //         return $e->response;
    //     }

    //     return $request->expectsJson()
    //     ? $this->invalidJson($request, $e)
    //     : $this->invalid($request, $e);
    // }

    protected function convertValidationExceptionToResponse(ValidationException $e, $request)
    {
        \Log::error('validator_error:', $request->all());
        if ($e->response) {
            return $e->response;
        }
        return $request->expectsJson()
            ? $this->invalidJson($request, $e)
            : $this->invalid($request, $e);
    }

    protected function unauthenticated($request, AuthenticationException $exception)
    {
        if (false !== array_search('admin', $exception->guards())) {
            return redirect(route('admin.login_form'));
        }
        // 浏览器 no-referrer-when-downgrade 策略 手动传入跳转链接
        $jumpUrl = route('login', ['origin_url' => $request->fullUrl()]);
        return redirect($jumpUrl);
    }
}
